package cc.yugu.yhdw.webserver.web.controller.security.hdw;

import cc.yugu.yhdw.common.annotation.ViewModel;
import cc.yugu.yhdw.common.domain.basic.AgentInfo;
import cc.yugu.yhdw.common.domain.basic.Passport;
import cc.yugu.yhdw.common.domain.basic.User;
import cc.yugu.yhdw.common.domain.hdw.*;
import cc.yugu.yhdw.common.entity.json.DataResult;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.json.PageResult;
import cc.yugu.yhdw.webserver.constant.AppConstEnum;
import cc.yugu.yhdw.webserver.service.basic.AgentService;
import cc.yugu.yhdw.webserver.service.basic.PassportService;
import cc.yugu.yhdw.webserver.service.hdw.*;
import cc.yugu.yhdw.webserver.web.controller.security.SecurityController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * 电池管理
 *
 * @Date:Created in 2018/7/26 9:34
 * @Author:
 * @Modified By: zxj 2018/7/26 9:34
 */
@Controller
@RequestMapping(value = "/security/hdw/battery")
public class BatteryController extends SecurityController {
    @Autowired
    BatteryService batteryService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    BatteryReportLogService batteryReportLogService;
    @Autowired
    ExchangeOrderService exchangeOrderService;
    @Autowired
    BatteryAgentService batteryAgentService;
    //zxj :新增运营商业务和代理商业务
    @Autowired
    AgentService agentService;
    @Autowired
    AgencyService agencyService;

    @Autowired
    PassportService passportService;
    /**
     * 包含故障电池判断
     * @Param [model, healthy]
     * @Return void
     * @Author zxj 2018/7/26
     */
    @RequestMapping(value = "index.htm")
    public void index(Model model, Integer healthy) {
        model.addAttribute("supplierList", supplierService.findByType(Supplier.Type.BATTERY.getValue()));
        model.addAttribute("statusList", Battery.Status.values());
        if (healthy != null && (healthy.equals(1) || healthy.equals(2))) {
            model.addAttribute("healthy", healthy);
        } else {
            model.addAttribute("healthy", 0);
        }
        model.addAttribute(MENU_CODE_NAME, AppConstEnum.Menu.MENU_03_02.getValue());
    }

    @RequestMapping(value = "page.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public PageResult page(Battery battery, HttpServletRequest request) {
        // 特殊bug 如果前端页面上的 运营商和代理商选择 “所有” ，则后台接受的是‘0’，要处理一下
        if (battery.getAgencyId() != null && battery.getAgencyId() == 0) {
            battery.setAgencyId(null);
        }
        if (battery.getAgentId() != null && battery.getAgentId() == 0) {
            battery.setAgentId(null);
        }
        if (request.getParameter("healthyFlag") != null) {
            // 故障电池过滤
            if ("1".equals(request.getParameter("healthyFlag"))) {
                battery.setHealthy(1);
            }
            // 异常电池过滤
            if ("2".equals(request.getParameter("healthyFlag"))) {
                battery.setHealthy(2);
            }
        }
        /*
        设计：(请求重构，舍弃vo.BatteryVO)
              1.权限管理（获取session中的登陆用户的信息）
              2.代理商-运营商-厂商-总部（数量级来排序）
         */
        // 正常的流程(业务重构，舍弃vo.batteryVO,请求不做分支)
        int type = getSessionUser(request).getType();
        // 运营商赋值
        if (type == User.Type.AGENT.getValue()) {
            battery.setAgentId(getSessionUser(request).getAgentId());
        }
        // 代理商赋值
        if (type == User.Type.AGENCY.getValue()) {
            battery.setAgencyId(getSessionUser(request).getAgencyId());
        }
        // 厂商赋值
        if (type == User.Type.SUPPLIER.getValue()) {
            battery.setSupplierId(getSessionUser(request).getSupplierId());
        }
        return PageResult.successResult(batteryService.findPage(battery));
    }

    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping("add.htm")
    public String add(Model model) {
        model.addAttribute("supplierList", supplierService.findByType(Supplier.Type.BATTERY.getValue()));
        return "/security/hdw/battery/add";
    }


    @RequestMapping("bound_card.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult boundCard(Battery entity) {
        return batteryService.boundCard(entity);
    }

    @ViewModel(ViewModel.INNER_PAGE)
    @RequestMapping(value = "edit.htm")
    public String edit(String id, Model model) {
        Battery battery = batteryService.find(id);
        // 新增:根据电池id查询hdw——battery_agent表中数据
        BatteryAgent batteryAgent = batteryAgentService.find(battery.getId());
        // 放入model
        model.addAttribute("batteryAgent",batteryAgent);
        model.addAttribute("entity", battery);
        model.addAttribute("supplierList", supplierService.findByType(Supplier.Type.BATTERY.getValue()));
        return "/security/hdw/battery/edit";
    }

    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "create.htm")
    public ExtResult create(Battery entity) {
        return batteryService.insert(entity);
    }
    /**
    * 新增方法：往两个不同表中插数据
    *
    * @Param: [entity, batteryAgent]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/26  15:57
    */
    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "createAgent.htm")
    public ExtResult createAgent(Battery entity,BatteryAgent batteryAgent) {

        return batteryService.insert(entity,batteryAgent);
    }
    /**
    * 更新表
    *
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/26  16:02
    */
    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "update.htm")
    public ExtResult update(Battery entity) {
        return batteryService.update(entity);
    }
    /**
    * 新增：更新两个表
    *
    * @Param: [entity]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/26  16:02
    */
    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "updateAgent.htm")
    public ExtResult updateAgent(Battery entity,BatteryAgent batteryAgent) {
        return batteryService.updateAgent(entity,batteryAgent);
    }
    /**
    * 查看电池信息
    *
    * @Param: [model, id]
    * @Return: java.lang.String
    * @Author By: zjn 2018/9/7  16:29
    */
    @RequestMapping(value = "view.htm")
    public String view(Model model, String id) {
        // 查询电池信息
        Battery entity = batteryService.find(id);
        // 查询运营商和代理商id
        BatteryAgent batteryAgent = batteryAgentService.find(id);
        // 运营商名称
        if (batteryAgent != null) {
            if (batteryAgent.getAgentId() != null) {
                AgentInfo agentInfo = agentService.findAgentName(batteryAgent.getAgentId());
                if (agentInfo.getAgentName() != null) {
                    model.addAttribute("agentName", agentInfo.getAgentName());
                }
            }
            if (batteryAgent.getAgencyId() != null) {
                AgencyInfo agencyInfo = agentService.findAgencyName(batteryAgent.getAgencyId());
                if (agencyInfo.getAgencyName() != null) {
                    model.addAttribute("agencyName", agencyInfo.getAgencyName());
                }
            }
        }
        // 查询客户真实姓名
        if(entity.getCustomerId()!=null&&entity.getCustomerId()!=0){
            String realName = passportService.find(entity.getCustomerId()).getRealName();
            if (realName == null) {
                return SEGMENT_RECORD_NOT_FOUND;
            } else {
                model.addAttribute("realName", realName);
            }
        }
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/hdw/battery/view";
    }

    @RequestMapping(value = "usageLog.htm")
    public void usageLog(Model model, String batteryId) {
        model.addAttribute("batteryId", batteryId);
    }

    @ViewModel(ViewModel.JSON)
    @ResponseBody
    @RequestMapping(value = "findUsageLog.htm")
    public ExtResult findUsageLog(Date date, String id) {
        List<String> entity = batteryService.findUsageLog(date, id);
        return DataResult.successResult(entity);
    }

    @ViewModel(ViewModel.JSON)
    @ResponseBody
    @RequestMapping(value = "findUsageLogCount.htm")
    public ExtResult findUsageLogCount(String id) {
        List<String> entity = batteryService.findUsageLogCount(id);
        return DataResult.successResult(entity);
    }
    @RequestMapping("delete.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult delete(String id) {
        batteryService.delete(id);
        return ExtResult.successResult();
    }
    /**
     * 电池管理中的定位操作
     * @Param [model, id]
     * @Return void
     * @Author zxj 2018/7/24
     */
    @RequestMapping(value = "battery_location.htm")
    public void battery_location(Model model, String id) {
        // 根据电池id查询电池信息
        Battery entity = batteryService.find(id);
        model.addAttribute("id", id);
        model.addAttribute("lng", entity.getLng());
        model.addAttribute("lat", entity.getLat());
        /**
         * 这个是一代的设计，通过电池id查询电池上传日志表中关联的订单id
         * 1.一代的电池日志上传都在一个表中(非常影响查询效率）
         * 2.二代的电池日志上传的重新设计，分表存储，导致这个查询出现空数据
         * 3.解决--去hdw_exchange_order（订单表）中查询	second_battery_id（取新电池的编号）关联两者的对应关系
         * 4.分析--这个方案要测试检验
         * 5.条件--换电订单的状态为完成（4）
         */
        //model.addAttribute("orderList", batteryReportLogService.findOrderId(id, null));
        ExchangeOrder exchangeOrder = new ExchangeOrder();
        exchangeOrder.setSecondBatteryId(id);
        exchangeOrder.setOrderStatus(4);
        model.addAttribute("orderList", exchangeOrderService.findOrderIds(exchangeOrder));
    }

    @RequestMapping(value = "select_battery.htm")
    public void selectBattery(Model model) {
    }
    /**
     * 电池分布图展示
     * @Param []
     * @Return cc.yugu.yhdw.common.entity.json.DataResult
     * @Author zxj 2018/8/21
     */
    @RequestMapping(value = "coordinate.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public DataResult coordinate() {
        return DataResult.successResult(batteryService.findAll());
    }
}
